<template>
    <topic-layout :list="list" title="视频详情" v-loading="loading">
        <div class="container" :class="{ 'is-mobile': $isMobile }">
            <div class="lessonInfos">
                <div class="lessonInfos-left">
                    <img :src="lessonInfos.coverImage" />
                </div>
                <div class="lessonInfos-right">
                    <div class="lessonInfos-title">{{ lessonInfos.title }}</div>
                    <div class="lessonInfos-nums"> 共 {{ datas.length }} 节课</div>
                    <div class="lessonInfos-desc">{{ lessonInfos.desc }}</div>

                    <div class="lessonInfos-duration">

                        <div>
                            课程总时长：
                            <span>{{ formatSecond(allDurations) }}</span>
                        </div>
                    </div>

                    <div class="lessonInfos-duration" v-if="userInfo && userInfo.id">
                        <div class="currentDurations"> 已学习时长：{{ formatSecond(currentDurations) }}
                        </div>
                    </div>


                    <div class="btn-exam" v-if="lessonInfos && lessonInfos.examId" @click="toResult(lessonInfos)">查看成绩
                    </div>

                    <div v-else class="btn-exam" @click="joinExam">参加考试</div>

                </div>
            </div>
            <div class="video-list__title">课程目录</div>

            <template v-if="datas && datas.length">
                <div class="video-list">
                    <div v-for="item in datas" :key="item.id" class="video-list__item" @click="openVideo(item)">
                        <div class="poster">
                            <img :src="item.poster" class="poster-content" />
                            <img src="../../assets/play.svg" class="play">
                        </div>
                        <div class="title">{{ item.title }}</div>
                        <img src="../../assets/vip.svg" class="isVip" v-if="item.type">
                    </div>
                </div>
            </template>

            <template v-else>
                <el-empty :image-size="200"></el-empty>
            </template>
        </div>

        <video-container v-if="videoVisible" :visible.sync="videoVisible" ref="videoontainer"
            @report="handleReport"></video-container>
    </topic-layout>
</template>

<script>

import videoContainer from '../../components/video-container.vue';
import topicLayout from '../../components/layout';
import { getUser } from "@/utils/auth.js";

export default {
    components: {
        topicLayout,
        videoContainer
    },
    data() {
        return {
            userInfo: {},
            lessonInfos: {},
            allDurations: 0,
            datas: [],
            list: [
                {
                    id: "lesson-video",
                    name: "视频课件",
                }
            ],
            loading: false,
            videoVisible: false,
            currntVideo: {},

            currentDurations: 0,

        };
    },

    async mounted() {

        await this.refresh();
        this.$loginBox.addEventListener(this.refresh);

    },

    methods: {

        async refresh() {
            this.userInfo = getUser();
            await this.getLessonInfos();
            this.getData();
            this.getUserStudyDuration()
        },

        async getLessonInfos() {
            this.loading = true;
            const { lessonId } = this.$route.query;

            const { data } = await this.$fetch.get(`/api/topic-lesson/${lessonId}`);

            this.lessonInfos = data;
            this.loading = false;

        },

        async getData() {
            this.loading = true;
            const { topicId, lessonId } = this.$route.query;
            const { data } = await this.$fetch.get(`/api/topic-lesson-video/list`, { topicId, lessonId });
            this.datas = data.filter((item) => {
                return item.streamingVideoLink
            });
            this.loading = false;

            console.log("this.datas", this.datas)

            this.allDurations = this.datas
                .filter(data => data.type !== 0)
                .reduce((total, data) => total + data.duration, 0);
        },

        async openVideo(item) {

            const callback = () => {
                this.videoVisible = true;
                this.$nextTick(() => {
                    this.$refs.videoontainer.init(item);
                    this.currntVideo = item;
                })
            }

            if (item.type) {
                const status = await this.checkAuth();
                if (status) {
                    callback()
                }
            } else {
                callback()
            }
        },

        async checkAuth() {
            const { lessonId } = this.$route.query;

            const { code } = await this.$fetch.post(`/api/topic-lesson/checkIsVip`, { lessonId });
            if (code === 0) {
                return true;
            } else {
                return false
            }
        },

        async joinExam() {

            await this.getUserStudyDuration();

            if (!this.currentDurations) {
                return this.$message.warning('请先学习完课程后参加考试');
            }

            if (this.currentDurations && this.allDurations * 0.6 > this.currentDurations) {
                return this.$message.warning('视频学习进度不足60%, 请继续学习后参加考试');
            }


            const { lessonId, topicId } = this.$route.query;

            try {

                const { data } = await this.$fetch.post(`/api/topic-lesson/startExam`, { topicId, lessonId });

                this.$router.push({
                    name: "lesson-exam-process",
                    query: {
                        examId: data.exams.id,
                        lessonId,
                    }
                })

            } catch (error) {

            }

        },

        toResult(data) {
            this.$router.push({
                name: "lesson-exam-result",
                query: {
                    examId: data.examId,
                }
            })
        },

        async getUserStudyDuration() {
            if (this.userInfo.id) {
                const { lessonId } = this.$route.query;
                const { data } = await this.$fetch.get(`/api/topic-lesson/getUserStudyDuration`, { lessonId });

                if (Array.isArray(data)) {
                    this.currentDurations = 0;
                    for (const item of data) {
                        this.currentDurations += item.duration;
                    }
                }
            }

        },


        async handleReport(datas) {
            if (this.currntVideo && this.currntVideo.type) {
                await this.$fetch.post(`/api/topic-lesson-video-logs/report`, {
                    videoId: this.currntVideo.id,
                    datas
                });
                this.getUserStudyDuration();
            }
        },

        formatSecond(seconds = 0) {

            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            const formattedHours = String(hours).padStart(2, '0');
            const formattedMinutes = String(minutes).padStart(2, '0');
            const formattedSeconds = String(remainingSeconds).padStart(2, '0');
            return `${formattedHours}时${formattedMinutes}分${formattedSeconds}秒`;
        }
    }

};
</script>

<style lang="less" scoped>
.container {
    margin: 20px;
}

.lessonInfos {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;

    .lessonInfos-left {
        width: 516px;
        height: 286px;
        margin-right: 20px;

        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }

    .lessonInfos-right {
        .lessonInfos-title {
            font-family: PingFangSC, PingFang SC;
            font-weight: 600;
            font-size: 24px;
            color: #333333;
            line-height: 33px;
            text-align: left;
            font-style: normal;
            margin-bottom: 20px;
        }

        .lessonInfos-nums {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #484848;
            line-height: 20px;
            text-align: left;
            font-style: normal;
            margin-bottom: 10px;
        }


        .lessonInfos-desc {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #AEAEAE;
            text-align: left;
            font-style: normal;
            white-space: pre;
            margin-bottom: 12px;
            line-height: 2;
        }

        .btn-exam {
            padding: 20px 64px;
            background: #3560AB;
            border-radius: 4px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 16px;
            color: #FFFFFF;
            line-height: 22px;
            text-align: center;
            font-style: normal;
            cursor: pointer;
        }

        .lessonInfos-duration {
            margin-bottom: 16px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 14px;
            color: #484848;
            line-height: 20px;
            text-align: left;
            font-style: normal;
            font-weight: bold;

            .currentDurations {
                color: #3560AB;
            }
        }
    }

}


.video-list__title {

    padding-top: 20px;
    padding-bottom: 10px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: 18px;
    color: #333333;
    line-height: 25px;
    text-align: left;
    font-style: normal;
    border-bottom: 1px solid #EFEFEF;
}


.video-list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;


    .video-list__item {
        margin-top: 20px;
        margin-right: 20px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        background: #F8F9FB;
        border-radius: 8px;
        position: relative;
        width: calc(25% - 20px);
        aspect-ratio: 4 / 3;


        .poster {
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, .1);
            position: relative;
            cursor: pointer;


            .poster-content {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }

            .play {
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                z-index: 2;
                width: 26px;
                height: 26px;
            }
        }


        .title {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #484848;
            line-height: 17px;
            text-align: center;
            font-style: normal;
            margin-top: 10px;
            margin-bottom: 10px;
            cursor: pointer;
        }

        .isVip {
            position: absolute;
            right: 5px;
            top: 5px;
            width: 24px;
            height: 24px;
        }

    }
}

.container.is-mobile {
    margin: 10px;

    .lessonInfos {
        display: flex;

        .lessonInfos-left {
            max-width: 50%;
            width: fit-content;
            margin-right: 0;
            height: fit-content;

            img {
                object-fit: cover;
            }
        }

        .lessonInfos-right {
            margin-left: 10px;

            .lessonInfos-title {
                margin-bottom: 6px;
                font-size: 16px;
                line-height: 22px;
            }

            .lessonInfos-nums {
                margin-bottom: 6px;
                font-size: 12px;
                line-height: 18px;
            }

            .lessonInfos-desc {
                line-height: 1;
                margin-bottom: 6px;

            }

            .btn-exam {
                padding: 6px;
                width: max-content;
                font-size: 14px;
            }

            .lessonInfos-duration {
                margin-bottom: 6px;
                font-size: 12px;
            }
        }
    }

    .video-list__title {
        padding: 10px 0;
    }

    .video-list {
        .video-list__item {
            width: calc(50% - 20px);
        }
    }


}
</style>